package com.example.travelsn.navigate;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Criteria;
import android.location.GpsSatellite;
import android.location.GpsStatus;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import com.example.travelsn.R;
import com.example.travelsn.util.LocationUtils;

import java.util.Iterator;

public class ConnateGPS extends AppCompatActivity implements View.OnClickListener {

    private boolean flag;
    private Button gsp_btn;
    private Button network_btn;
    private Button best_btn;
    private TextView countN;//获取LocationManager
    private Location mLocation;
    private static Context context;
    private int count = 0;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_innategps);
        context = getApplicationContext();
        initView();
        initListener();

    }

    private void initListener() {
        gsp_btn.setOnClickListener(this);
        network_btn.setOnClickListener(this);
        best_btn.setOnClickListener(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        initPermission();//针对6.0以上版本做权限适配
    }

    private void initView() {
        gsp_btn = (Button) findViewById(R.id.gps);
        network_btn = (Button) findViewById(R.id.net);
        best_btn = (Button) findViewById(R.id.best);
        countN = (TextView) findViewById(R.id.count);
    }

    private void initPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            //检查权限
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED
                    || ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                //请求权限
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION}, 1);
            } else {
                flag = true;
            }
        } else {
            flag = true;
        }
    }

    /**
     * 权限的结果回调函数
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 1) {
            flag = grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[1] == PackageManager.PERMISSION_GRANTED;
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.gps:
                if (flag) {
                    getGPSLocation();
                } else {
                    Toast.makeText(this, "no permission", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.net:
                if (flag) {
                    getNetworkLocation();
                } else {
                    Toast.makeText(this, "no permission", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.best:
                if (flag) {
                    getBestLocation();
                } else {
                    Toast.makeText(this, "no permission", Toast.LENGTH_SHORT).show();
                }
                break;
        }
    }

    /**
     * 通过GPS获取定位信息
     */
    @Deprecated
    public void getGPSLocationO() {
        final Location gps = LocationUtils.getGPSLocation(this);
        if (gps == null) {
            //设置定位监听，因为GPS定位，第一次进来可能获取不到，通过设置监听，可以在有效的时间范围内获取定位信息
            LocationUtils.addLocationListener(this, LocationManager.GPS_PROVIDER, new LocationUtils.ILocationListener() {
                @Override
                public void onSuccessLocation(Location location) {
                    if (location != null) {
                        System.out.println("GPS定位");
                        printLocation(location);
                    } else {
                        Toast.makeText(ConnateGPS.this, "gps location is null", Toast.LENGTH_SHORT).show();
                    }
                }
            });
        } else {
            getNetworkLocation();
        }
    }

    /**
     * 通过网络等获取定位信息
     */
    private void getNetworkLocation() {
        Location net = LocationUtils.getNetWorkLocation(this);
        if (net == null) {
            Toast.makeText(this, "net location is null", Toast.LENGTH_SHORT).show();
        } else {
            printLocation(net);
            //Toast.makeText(this, "network location: lat==" + net.getLatitude() + "  lng==" + net.getLongitude(), Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 采用最好的方式获取定位信息
     */
    private void getBestLocation() {
        Criteria c = new Criteria();//Criteria类是设置定位的标准信息（系统会根据你的要求，匹配最适合你的定位供应商），一个定位的辅助信息的类
        c.setPowerRequirement(Criteria.POWER_LOW);//设置低耗电
        c.setAltitudeRequired(false);//设置需要海拔
        c.setCostAllowed(true);
        c.setAccuracy(Criteria.ACCURACY_LOW);//设置低精度
        //... Criteria 还有其他属性，就不一一介绍了
        Location best = LocationUtils.getBestLocation(this, c);
        if (best == null) {
            Toast.makeText(this, " best location is null", Toast.LENGTH_SHORT).show();
        } else {
            printLocation(best);
        }
    }

    private void printLocation(Location location) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("定位信息");
        builder.setMessage("当前方向" + location.getBearing() + "\n"
                + "经度：" + location.getLongitude() + "  纬度：" + location.getLatitude() + "\n"
                + "高度" + location.getAltitude() + "\n" +
                "");
        builder.show();
    }
    /**
     * 通过GPS获取定位信息
     */
    private void getGPSLocation()
    {
        //获取系统的LocationManager对象
        final LocationManager mLocationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
        try
        {
            mLocation = mLocationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
            printLocation(mLocation);
            mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 10, new LocationListener() {
                @Override
                public void onLocationChanged(Location location)
                {
                    printLocation(location);
                }
                @Override
                public void onStatusChanged(String provider, int status, Bundle extras)
                {
                }
                @Override
                public void onProviderEnabled(String provider)
                {
                }
                @Override
                public void onProviderDisabled(String provider)
                {

                }
            });
        }
        catch (SecurityException e)
        {
            e.printStackTrace();
        }
    }

}


